package com.jichaoyun.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jichaoyun.common.model.PagedResult;
import com.jichaoyun.common.model.Result;
import com.jichaoyun.dao.mapper.LineInfoMapper;
import com.jichaoyun.dao.mapper.RealdataCacheMapper;
import com.jichaoyun.model.entity.LineInfo;
import com.jichaoyun.model.entity.LowParaConfigue;
import com.jichaoyun.model.entity.RealdataCache;
import com.jichaoyun.model.entity.StationInfo;
import com.jichaoyun.dao.mapper.RoleMapper;
import com.jichaoyun.dao.mapper.StationInfoMapper;
import com.jichaoyun.model.vo.MultiRealInfoVo;
import com.jichaoyun.model.vo.SomeStationFlowTotal;
import com.jichaoyun.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@RestController
@Api(tags = {"多用户信息接口"})
@RequestMapping("/sys/MultiUserInfo")
public class MultiUserController {
    @Autowired
    private IStationInfoService stationInfoService;

    @Autowired
    private IRealdataService realdataService;

    @Autowired
    private LineInfoService lineInfoService;

    @Autowired
    private ILowParaConfigueService lowParaConfigueService;

    @Autowired
    private IFlowMonthService flowMonthService;

    @Autowired
    private IFlowDayService flowDayService;

    @Autowired
    private IRealdataCacheService realdataCacheService;

    @ApiOperation("多用户信息，用户数量，查询各线路用户分布情况")
    @GetMapping("/getUserLineDistribution")
    public Result<Map<String,Integer>> getUserLineDistribution() {
        return Result.success(stationInfoService.getUserLineDistribution());
    }

    @ApiOperation("多用户信息，用户数量占比，查询用户类别情况")
    @GetMapping("/getUserCategory")
    public Result<Map<String,Integer>> getUserCategory() {
        return Result.success(stationInfoService.getUserCategory());
    }

    @ApiOperation("多用户信息，报警用户占比，查询用户报警占比情况")
    @GetMapping("/getUserAlarmProportion")
    public Result<Map<String,Long>> eachAlarmProportion() {
        return Result.success(realdataService.eachAlarmProportion());
    }

    @ApiOperation("多用户信息，今日流量分布，查询昨日线路流量分布情况")
    @GetMapping("/getLineFlowDayProportion")
    public Result<Map<String,Float>> getLineFlowDayProportion() {
        return Result.success(lineInfoService.getLineFlowDay());
    }

    @ApiOperation("多用户信息，本月流量分布，查询月份线路流量分布情况")
    @GetMapping("/getLineFlowMonthProportion")
    public Result<Map<String,Float>> getLineFlowMonthProportion() {
        return Result.success(lineInfoService.getLineFlowMonth());
    }

    @ApiOperation("多用户信息，本年流量分布，查询年度线路流量分布情况")
    @GetMapping("/getLineFlowYearProportion")
    public Result<Map<String,Float>> getLineFlowYearProportion() {
        return Result.success(lineInfoService.getLineFlowYear());
    }
    @ApiOperation("多用户信息，今日流量排名，查询昨日流量排名")
    @GetMapping("/getDayFlowRank")
    public Result<Map<String,Map<Float,Integer>>> getDayFlowRank() {
        return Result.success(lineInfoService.getDayFlowRank());
    }

    @ApiOperation("多用户信息，本月流量排名，查询月份流量排名")
    @GetMapping("/getMonthFlowRank")
    public Result<Map<String,Map<Float,Integer>>> getMonthFlowRank() {
        return Result.success(lineInfoService.getMonthFlowRank());
    }

    @ApiOperation("多用户信息，本年流量排名，查询年度流量排名")
    @GetMapping("/getYearFlowRank")
    public Result<Map<String,Map<Float,Integer>>> getYearFlowRank() {
        return Result.success(lineInfoService.getYearFlowRank());
    }


    @ApiOperation("多用户信息，前月用气，对比上月与前月用气量")
    @GetMapping("/getGasCompareMonth")
    public Result<Map<String,Float>> getGasCompareMonth(Integer station_no) {
        return Result.success(flowMonthService.getMonthSteamComparison(station_no));
    }

    @ApiOperation("多用户信息，上年同月用气，对比上月与去年同月份用气量")
    @GetMapping("/getSameMonthSteamComparison")
    public Result<Map<String,Float>> getSameMonthSteamComparison(Integer station_no) {
        return Result.success(flowMonthService.getSameMonthSteamComparison(station_no));
    }

    @Autowired
    private LineInfoMapper lineInfoMapper;

    @Autowired
    private StationInfoMapper stationInfoMapper;
    @Autowired
    private RealdataCacheMapper realdataCacheMapper;

    @ApiOperation("数据总览")
    @GetMapping("/getOverViewList")
    public Result<List<Map<String,Object>>> getOverViewList() {
        List<Map<String, Object>> res = new ArrayList<>();
        LambdaQueryWrapper<LineInfo> wrapper = new LambdaQueryWrapper<>();
        //屏蔽四通道表
        wrapper.ne(LineInfo::getLineNum,23);
        List<LineInfo> lineInfos = lineInfoMapper.selectList(wrapper);
        float allMain = 0f;
        float allSub = 0f;
        for (LineInfo lineInfo : lineInfos) {
            String lineName =  (lineInfo.getLineAlias()==null|| lineInfo.getLineAlias().equals("")) ?lineInfo.getLineName() :lineInfo.getLineAlias();
            //该路线的总表的和
            LambdaQueryWrapper<StationInfo> wp = new LambdaQueryWrapper<>();
            wp.eq(StationInfo::getUserType,0).eq(StationInfo::getLineId,lineInfo.getLineNum());
            List<StationInfo> mainStationInfoList = stationInfoMapper.selectList(wp);
            float mainTotal =0f;
            for (StationInfo stationInfo : mainStationInfoList) {
                RealdataCache realdataCache = realdataCacheMapper.selectRecentOneByStation(stationInfo.getStationNo());
                if(realdataCache==null){
                    mainTotal+=0;
                    continue;
                }
                if(realdataCache.getFlow()!=null)
                    mainTotal+=realdataCache.getFlow();
            }
            HashMap<String, Object> map1 = new LinkedHashMap<>();
            map1.put("项目",lineName+"(总表合计)");
            map1.put("流量(t/h)",String.format("%.3f",mainTotal));
            //该路线的分表的和
            LambdaQueryWrapper<StationInfo> wp1 = new LambdaQueryWrapper<>();
            wp1.eq(StationInfo::getUserType,1).eq(StationInfo::getLineId,lineInfo.getLineNum());
            List<StationInfo> subStationInfoList = stationInfoMapper.selectList(wp1);
            float subTotal =0f;
            for (StationInfo stationInfo : subStationInfoList) {
                RealdataCache realdataCache = realdataCacheMapper.selectRecentOneByStation(stationInfo.getStationNo());
                if(realdataCache==null){
                    mainTotal+=0;
                    continue;
                }
                if(realdataCache.getFlow()!=null)
                    subTotal+=realdataCache.getFlow();
            }
            HashMap<String, Object> map2 = new LinkedHashMap<>();
            map2.put("项目",lineName+"(分表合计)");
            map2.put("流量(t/h)",String.format("%.3f",subTotal));
            map2.put("管损(t)","");
            map2.put("管损率(%)","");

            map1.put("管损(t)",mainTotal-subTotal);
            if (mainTotal!=0){
                map1.put("管损率(%)",String.format("%.3f",(mainTotal-subTotal)*100/mainTotal));
            }else{
                map1.put("管损率(%)","");
            }
            res.add(map1);
            res.add(map2);
            allMain+=mainTotal;
            allSub+=subTotal;
        }
        HashMap<String, Object> map3 = new LinkedHashMap<>();
        map3.put("项目","热网所有总表合计");
        map3.put("流量(t/h)",String.format("%.3f",allMain));
        map3.put("管损(t)",String.format("%.3f",allMain-allSub));
        if (allMain!=0){
            map3.put("管损率(%)",String.format("%.3f",(allMain-allSub)*100/allMain));
        }else{
            map3.put("管损率(%)","");
        }
        res.add(map3);

        HashMap<String, Object> map4 = new LinkedHashMap<>();
        map4.put("项目","热网所有分表合计");
        map4.put("流量(t/h)",String.format("%.3f",allSub));
        map4.put("管损(t)","");
        map4.put("管损率(%)","");
        res.add(map4);
        return Result.success(res);
    }


    @ApiOperation("智慧看板总累计流量、实时流量")
    @GetMapping("/getOverFlow")
    public Result<List<Map<String,Object>>> getOverFlow() {

        return Result.success(stationInfoService.getOverFlow());
    }


    @ApiOperation("智慧看板三个厂的流量数据")
    @GetMapping("/getThreeFlowUpAndDown")
    public Result<List<Map<String,Object>>> getThreeFlowUpAndDown() {

       return Result.success(stationInfoService.getThreeFlowUpAndDown());
    }

    @ApiOperation("智慧看板煤化工园区高压流量")
    @GetMapping("/getFiveFlowHigh")
    public Result<List<Map<String,Object>>> getFiveFlowHigh() {

        return Result.success(stationInfoService.getFiveFlowHigh());
    }

    @ApiOperation("智慧看板煤化工园区低压流量")
    @GetMapping("/getFiveFlowLow")
    public Result<List<Map<String,Object>>> getFiveFlowLow() {

        return Result.success(stationInfoService.getFiveFlowLow());
    }

    @ApiOperation("智慧看板煤化工园区流量")
    @GetMapping("/getTenFlow")
    public Result<List<Map<String,Object>>> getTenFlow() {

        return Result.success(stationInfoService.getTenFlow());
    }

//    @ApiOperation(value = "多用户信息，多用户实时数据，查询多用户实时信息列表(这里是带条件筛选的）,分页",notes = "" +
//            "lineid 全部传入-1，identiy传入flow temp pres 这三种字符串，升序asc 降序desc ")
//    @GetMapping("/getMultiRealInfoListBy")
//    public Result<PagedResult> getMultiRealInfoListBy(Integer lineId,String identity,String sort , Integer pageNo, Integer pageSize) {
//        PagedResult pagedResult = realdataCacheService.getMultiRealInfovoBy(lineId,identity,sort, pageNo,pageSize);
//        List<MultiRealInfoVo> multiRealInfoVoList = new ArrayList<>();
//        //进行到vo返回的转化
//        for (Object row : pagedResult.getRows()) {
//            MultiRealInfoVo infoVo = new MultiRealInfoVo();
//            BeanUtils.copyProperties(row,infoVo);
//            multiRealInfoVoList.add(infoVo);
//        }
//        pagedResult.setRows(multiRealInfoVoList);
//        return Result.success(pagedResult);
//    }
    @ApiOperation(value = "多用户信息，多用户实时数据，查询多用户实时信息列表(这里是带条件筛选的）,不分页",notes = "" +
            "lineid 全部传入-1，identiy传入flow temp pres 这三种字符串，升序asc 降序desc ")
    @GetMapping("/getMultiRealInfoListBy")
    public Result<List<MultiRealInfoVo>> getMultiRealInfoListBy(Integer lineId,String identity,String sort) {
        ArrayList<RealdataCache> multiRealInfovoBy = realdataCacheService.getMultiRealInfovoBy(lineId, identity, sort);
        List<MultiRealInfoVo> multiRealInfoVoList = new ArrayList<>();
        //进行到vo返回的转化
        for (Object row : multiRealInfovoBy) {
            MultiRealInfoVo infoVo = new MultiRealInfoVo();
            BeanUtils.copyProperties(row,infoVo);
            multiRealInfoVoList.add(infoVo);
        }
        return Result.success(multiRealInfoVoList);
    }

    @ApiOperation(value = "自定义用量报表，分页查询",notes = "date格式yyyy-MM-dd HH:mm:ss，默认查10条数据")
    @GetMapping("/getTablePeriod")
    public Result<PagedResult> getTablePeriod(Integer pageNo,String start,String end){
        PagedResult pagedResult = new PagedResult();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime s = LocalDateTime.parse(start,dateTimeFormatter);
        LocalDateTime e = LocalDateTime.parse(end,dateTimeFormatter);
        pagedResult =  realdataService.getTablePeriod(pageNo,s,e);
        return Result.success(pagedResult);
    }


    @ApiOperation(value = "三个厂的总体记录查询",notes = "date格式yyyy-MM-dd HH:mm:ss")
    @GetMapping("/getThreeTablePeriod")
    public Result<List<SomeStationFlowTotal>> getThreeTablePeriod(String start, String end){

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime s = LocalDateTime.parse(start,dateTimeFormatter);
        LocalDateTime e = LocalDateTime.parse(end,dateTimeFormatter);
        return Result.success(realdataService.getThreeTablePeriod(s,e));
    }


    @ApiOperation(value = "三个厂的详细记录查询，分页查询",notes = "date格式yyyy-MM-dd HH:mm:ss，默认查10条数据，pageNo不能设置为0")
    @GetMapping("/getThreeTablePeriodDetail")
    public Result<PagedResult> getThreeTablePeriodDetail(Integer pageNo,Integer pageSize,String type,String start,String end){
        PagedResult pagedResult = new PagedResult();

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime s = LocalDateTime.parse(start,dateTimeFormatter);
        LocalDateTime e = LocalDateTime.parse(end,dateTimeFormatter);
        pagedResult =  realdataService.getThreeTablePeriodDetail(pageNo,pageSize,type,s,e);
        return Result.success(pagedResult);
    }




    @ApiOperation(value = "自定义用量报表，导出到excel",notes = "date格式yyyy-MM-dd HH:mm:ss")
    @GetMapping("/getTablePeriodExcel")
    public void getTablePeriod(String start,String end,HttpServletResponse response) throws IOException {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime s = LocalDateTime.parse(start,dateTimeFormatter);
        LocalDateTime e = LocalDateTime.parse(end,dateTimeFormatter);
        realdataService.getTablePeriodExcel(s,e,response);
    }

    /**
     * zz
     * @param pageNo
     * @param startTime
     * @param endTime
     * @return
     */
    @ApiOperation(value = "多用户信息，低计量参数设置，分页查询某时间区间低计量参数的显示结果",notes = "日期格式yyyy-MM-dd HH:00:00，精确到小时就好了")
    @GetMapping("/getPeriodInfoPage")
    public Result<PagedResult> getPeriodInfoPage(Integer pageNo,String startTime,String endTime) {
//        startTime = "2023-09-10 12:00:00";
//        endTime = "2023-11-30 23:00:00";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime start = LocalDateTime.parse(startTime,dateTimeFormatter);
        LocalDateTime end = LocalDateTime.parse(endTime,dateTimeFormatter);

        PagedResult pagedResult = realdataService.getPeriodInfoPage(pageNo,start,end);

        return Result.success(pagedResult);
    }

    /**
     * zz
     * @param lowParaConfigue
     * @return
     */
    @ApiOperation("多用户信息，低计量参数设置，修改某时间区间低计量参数的显示结果保存到数据库")
    @PostMapping("/AlterPeriodFlow")
    public Result<PagedResult> AlterPeriodFlow(@RequestBody LowParaConfigue lowParaConfigue) {
         if(lowParaConfigueService.save(lowParaConfigue)){
             return Result.success("修改成功");
         }else{
             return Result.fail("修改失败");
         }
    }

    @ApiOperation(value = "多用户信息，低计量参数设置，低计量参数设置导出到excel",notes = "日期格式yyyy-MM-dd HH:00:00，精确到小时就好了")
    @GetMapping("/DownloadPeriodInfoPage")
    public void DownloadPeriodInfoPage(String startTime, String endTime, HttpServletResponse response) throws IOException {
//        startTime = "2023-09-10 12:00:00";
//        endTime = "2023-11-30 23:00:00";
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime start = LocalDateTime.parse(startTime,dateTimeFormatter);
        LocalDateTime end = LocalDateTime.parse(endTime,dateTimeFormatter);

        realdataService.getPeriodInfo(start,end,response);

    }



    /**
     * zz
     * @param date
     * @param pageNo
     * @return
     */
    @ApiOperation(value = "多用户信息，多用户日报表，分页查询全部用户，根据日期获取",notes = "date格式yyyy-MM-dd，默认查10条数据")
    @GetMapping("/getMultiStationDayFormPage")
    public Result<PagedResult> getMultiStationDayFormPage(String date,Integer pageNo){

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date1 = LocalDate.parse(date,dateTimeFormatter);
        LocalDateTime theDay = date1.atStartOfDay();

        PagedResult pagedResult =  flowDayService.getAllMultiStationDayFormPage(theDay,pageNo);

        return Result.success(pagedResult);
    }

    @ApiOperation(value = "多用户信息，多用户日报表，导出全部的用户到Excel",notes = "date格式yyyy-MM-dd，默认查10条数据")
    @GetMapping("/DownloadDaily")
    public void DownloadDaily(String date,HttpServletResponse response) throws IOException {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date1 = LocalDate.parse(date,dateTimeFormatter);
        LocalDateTime theDay = date1.atStartOfDay();

        flowDayService.getAllMultiStationDayForm(theDay,response);

    }

    /**
     * zz
     * @param date
     * @param stationNo
     * @return
     */
    @ApiOperation(value = "多用户信息，多用户日报表，根据站号、日期查询多用户中日报表",notes = "date格式yyyy-MM-dd")
    @GetMapping("/getMultiStationDayFormByStation")
    public Result<Map<String,Object>> getMultiStationDayFormByStation(String date,Integer stationNo){

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate date1 = LocalDate.parse(date,dateTimeFormatter);
        LocalDateTime theDay = date1.atStartOfDay();

        Map<String,Object> resMap =  flowDayService.getMultiStationDayFormByStation(theDay,stationNo);

        return Result.success(resMap);
    }

    /**
     * zz
     * @param month
     * @param year
     * @param pageNo
     * @return
     */
    @ApiOperation(value = "多用户信息，多用户月报表，分页查询全部的多用户月报表",notes = "可以查询本月，默认查10条数据")
    @GetMapping("/getMultiStationMonthFormPage")
    public Result<PagedResult> getMultiStationMonthFormPage(Integer month,Integer year,Integer pageNo){

        LocalDateTime theDay = LocalDateTime.of(year,month,1,0,0,0);

        PagedResult pagedResult =  flowMonthService.getMultiStationMonthFormPage(theDay,pageNo);

        return Result.success(pagedResult);
    }

    @ApiOperation(value = "多用户信息，多用户月报表，导出全部的用户到Excel")
    @GetMapping("/DownloadMonthly")
    public void DownloadMonthly(Integer month,Integer year,HttpServletResponse response) throws IOException {

        LocalDateTime theDay = LocalDateTime.of(year,month,1,0,0,0);

        flowMonthService.getMultiStationMonthForm(theDay,response);

    }



    /**
     * zz
     * @param month
     * @param year
     * @param stationNo
     * @return
     */
    @ApiOperation(value = "多用户信息，多用户月报表，根据站号查询的多用户月报表",notes = "可以查询本月")
    @GetMapping("/getMultiStationMonthFormByStation")
    public Result<Map<String,Object>> getMultiStationMonthFormByStation(Integer month,Integer year,Integer stationNo){

        LocalDateTime theDay = LocalDateTime.of(year,month,1,0,0,0);

        Map<String,Object> res =  flowMonthService.getMultiStationMonthFormByStation(theDay,stationNo);

        return Result.success(res);
    }

    /**
     * zz
     * @param year
     * @param pageNo
     * @return
     */
    @ApiOperation(value = "多用户信息，多用户年报表，分页查询多用户年报表",notes = "可以查询本年")
    @GetMapping("/getMultiStationYearFormPage")
    public Result<PagedResult> getMultiStationYearFormPage(Integer year,Integer pageNo){

        LocalDateTime theDay = LocalDateTime.of(year,1,1,0,0,0);

        PagedResult pagedResult =  flowMonthService.getMultiStationYearFormPage(theDay,pageNo);

        return Result.success(pagedResult);
    }

    @ApiOperation("多用户信息，多用户年报表，根据站号查询的多用户年报表")
    @GetMapping("/getSingleStationYearForm")
    public Result<Map<String,Object>> getSingleStationYearForm(Integer Station_no, Integer year){


        Map<String,Object> resMap = new HashMap<>();

        resMap.put("用户站号",Station_no);
        resMap.put("用户站名",this.stationInfoService.getById(Station_no).getStationName());
        resMap.put("每月用汽集合",flowMonthService.getStationYearForm(Station_no, year));

        return Result.success(resMap);

    }

    @ApiOperation(value = "多用户信息，多用户年报表，导出全部的用户到Excel")
    @GetMapping("/DownloadYearly")
    public void DownloadYearly(Integer year,HttpServletResponse response) throws IOException {

        LocalDateTime theDay = LocalDateTime.of(year,1,1,0,0,0);

        flowMonthService.getMultiStationYearForm(theDay,response);

    }



    @ApiOperation(value = "//修改本月结算汽量并保存",notes = "前端可以设计成失焦就保存")
    @PostMapping("/updateMultiStationMonthFlowSettle")
    public Result<?> updateMultiStationMonthFlowSettle(Integer year,Integer month, Float flow,Integer stationNo){

        LocalDateTime theDay = LocalDateTime.of(year,month,1,0,0,0);

        Integer change =  flowMonthService.updateMultiStationMonthFlowSettle(theDay,flow,stationNo);
        if (change ==1){
            return Result.success("修改成功");
        }else{
            return Result.fail("修改失败");
        }

    }

    /**
     * 月度同比分析,分页查找所有
     * @param month
     * @param year
     * @param pageNo
     * @return
     */
    @ApiOperation(value = "多用户信息，月度同比分析,分页查找所有",notes = "可以查询本月，默认查10条数据")
    @GetMapping("/getMultiStationTBMonthFormPage")
    public Result<PagedResult> getMultiStationTBMonthFormPage(Integer month,Integer year,Integer pageNo){

        LocalDateTime theDay = LocalDateTime.of(year,month,1,0,0,0);

        PagedResult pagedResult =  flowMonthService.getMultiStationTBMonthFormPage(theDay,pageNo);

        return Result.success(pagedResult);
    }


    /**
     * 月度同比分析,根据站号查找一条数据
     * @param month
     * @param year
     * @param stationNo
     * @return
     */
    @ApiOperation(value = "多用户信息，月度同比分析,根据站号查找一条数据",notes = "可以查询本月")
    @GetMapping("/getMultiStationTBMonthFormByStation")
    public Result<Map<String,Object>> getMultiStationTBMonthFormByStation(Integer month,Integer year,Integer stationNo){

        LocalDateTime theDay = LocalDateTime.of(year,month,1,0,0,0);

        Map<String,Object> res =  flowMonthService.getMultiStationTBMonthFormByStation(theDay,stationNo);

        return Result.success(res);
    }







}
